import {create} from "zustand";
import {immer} from 'zustand/middleware/immer'
import {persist, devtools} from 'zustand/middleware'
import {setCookieToken, removeCookieToken} from "@/utils/auth";
import type {useUserStoreType, useSettersStoreType} from "@/typings/store";
import {useMenuStore} from "@/store/menu";
import {useTabsStore} from "@/store/tabs";


const initialState: useUserStoreType.stateType = {
    token: '',
    userInfo: {},
    authButtonList: [],
    authRoleList: []
}

const actions = (set: useSettersStoreType<useUserStoreType.storeType>) => {

    const setToken = (token: string) => {
        setCookieToken(token)
        set((state: useUserStoreType.stateType) => {
            state.token = token
        })
    }
    const setUserInfo = (payload: Record<string, any>) => {
        set((state: useUserStoreType.stateType) => {
            state.userInfo = payload.userInfo
        })
    }
    const setAuthPermission = (payload: Record<string, any>) => {
        set((state: useUserStoreType.stateType) => {
            state.authButtonList = payload.permissions
        })
    }
    const setAuthRole = (payload: Record<string, any>) => {
        set((state: useUserStoreType.stateType) => {
            state.authRoleList = payload.roles
        })
    }
    const signOut = () => {
        const {clearAuthMenu} = useMenuStore.getState()
        const {closeMultipleTab} = useTabsStore.getState()
        set((state: useUserStoreType.stateType) => {
            state.token = ''
            state.userInfo = {}
            state.authButtonList = []
            state.authRoleList = []
        })
        removeCookieToken()
        clearAuthMenu()
        closeMultipleTab({})
    }
    return {setToken, setUserInfo, setAuthPermission, setAuthRole, signOut}
}

const storage = {name: 'user-storage'}
export const useUserStore = create<useUserStoreType.storeType>()(devtools(persist(immer((set) => ({
    ...initialState,
    ...actions(set)
})), storage), storage))
